package com.sports.demo.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 * 图片上传
 * </p>
 *
 * @author SRG
 * @since 2022-03-13
 */
@RestController
@RequestMapping("/admin")
public class UploadController {
  /**
   * 上传用户反馈图片
   *
   * @author sunran
   */
  @ResponseBody
  @PostMapping("/upload")
  public Object uploadPicture(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
    String result = null;
    int maxSize = 1024 * 1024 * 1;    //上传最大为1MB
    if (file.getSize() > maxSize) {
      result="最大上传限制1Mb";
      return result;
    }
    File targetFile = null;
    String url = "";//返回存储路径
    String fileName = file.getOriginalFilename();//获取文件名加后缀
    if (fileName != null && fileName != "") {
      String path = "C:/data/file";
      String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
      if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".image"))) {
        result="只能上传jpg,jpeg,png,image格式";
        return result;
      }
      //新的文件名
      fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + fileF;
      //获取文件夹路径
      File file1 = new File(path);
      //如果文件夹不存在则创建
      if (!file1.exists() && !file1.isDirectory()) {
        file1.mkdirs();
      }
      //将图片存入文件夹
      targetFile = new File(file1, fileName);
      try {
        //将上传的文件写到服务器上指定的文件。
        file.transferTo(targetFile);
        //赋予权限
        String command = "" + targetFile;
        Runtime runtime = Runtime.getRuntime();
       // Process proc = runtime.exec(command);
        //生成文件地址
        url = "http://localhost:8090/file/" + fileName;
        System.out.println("图片上传成功 url:" + url);
        result=url;
      } catch (Exception e) {
        e.printStackTrace();
        result="系统异常，图片上传失败";
      }
    }
    return result;
  }
}
